/*
 *  Copyright 2011 Alexey Andreev.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.xthl.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.nop.core.Application;
import org.nop.core.ApplicationHandler;
import org.nop.sql.CloseableDataManager;
import org.nop.sql.DataManagerFactory;
import org.nop.sql.DataResult;
import org.nop.sql.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xthl.core.data.MenuItemSource;

/**
 * 
 * @author Alexey Andreev
 */
public class MenuFeatureImpl implements MenuFeature {
    private static final Logger logger = LoggerFactory.getLogger(MenuFeatureImpl.class);
    private Application app;
    private Set<Class<? extends MenuItemRenderer>> specialItems =
            new HashSet<Class<? extends MenuItemRenderer>>();

    public MenuFeatureImpl(Application app) {
        this.app = app;
        app.addApplicationHandler(new ApplicationHandler() {
            @Override
            public void started() {
                start();
            }
        });
    }

    @Override
    public void registerItem(Class<? extends MenuItemRenderer> item) {
        if (!app.isLoading()) {
            throw new IllegalStateException("Application already loaded");
        }
        if (specialItems.add(item)) {
            logger.info("Special menu item " + item.getName() + " registered");
        }
    }
    
    private void start() {
        CloseableDataManager dataManager = app.get(DataManagerFactory.class).createDataManager();
        try {
            QueryBuilder qb = dataManager.getQueryBuilder();
            MenuItemSource item = qb.get(MenuItemSource.class);
            
            logger.info("Creating menu items");
            DataResult result = dataManager.exec(qb.with(item)
                    .fetch(qb.max(item.position())));
            result.next();
            int pos = result.getInt(1) + 1;
            List<Class<? extends MenuItemRenderer>> specialItemList = 
                    new ArrayList<Class<? extends MenuItemRenderer>>(specialItems);
            Collections.sort(specialItemList, new Comparator<Class<? extends MenuItemRenderer>>() {
                @Override
                public int compare(Class<? extends MenuItemRenderer> o1,
                        Class<? extends MenuItemRenderer> o2) {
                    return o1.getName().compareTo(o2.getName());
                }                
            });
            int batchSize = 100;
            for (int i = 0; i < specialItemList.size(); i += batchSize) {
                int top = Math.min(i + batchSize, specialItemList.size());
                List<Class<? extends MenuItemRenderer>> batch = specialItemList.subList(i, top);
                Set<String> stringBatch = new HashSet<String>();
                for (Class<? extends MenuItemRenderer> itemGen : batch) {
                    stringBatch.add(itemGen.getName());
                }
                result = dataManager.exec(qb.with(item)
                        .filter(item.type().eq(MenuItemSource.SPECIAL_TYPE))
                        .filter(item.target().inStrings(stringBatch))
                        .fetch(item.target()));
                while (result.next()) {
                    stringBatch.remove(result.getString(1));
                }
                for (String className : stringBatch) {
                    int id = dataManager.nextInt(MenuItemSource.ID_SEQUENCE);
                    dataManager.exec(qb.insertInto(item)
                            .field(item.id(), id)
                            .field(item.type(), MenuItemSource.SPECIAL_TYPE)
                            .field(item.target(), className)
                            .field(item.enabled(), false)
                            .field(item.position(), pos++)
                            .field(item.title(), ""));
                }
            }
            dataManager.commit();
        } finally {
            dataManager.close();
        }
    }
}
